package com.freeLearning.boot.common.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;

public class WatermarkUtils {

    public static InputStream addWatermark(InputStream inputStream, String text) throws Exception {
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(inputStream);

        // 创建一个新的图片，用于添加水印
        BufferedImage watermarkedImage = new BufferedImage(
                originalImage.getWidth(),
                originalImage.getHeight(),
                BufferedImage.TYPE_INT_ARGB
        );
        Graphics2D graphics = watermarkedImage.createGraphics();
        graphics.drawImage(originalImage, 0, 0, null);

        // 设置水印字体和颜色
        Font font = new Font("Arial", Font.BOLD, 30);
        graphics.setFont(font);
        graphics.setColor(new Color(255, 255, 255, 100)); // 半透明白色

        // 计算水印位置（斜向）
        int x = 0;
        int y = 0;
        int angle = 45; // 斜向角度
        int textWidth = graphics.getFontMetrics().stringWidth(text);
        int textHeight = graphics.getFontMetrics().getHeight();

        // 添加多行斜向水印
        while (y < originalImage.getHeight()) {
            graphics.rotate(Math.toRadians(angle), x, y);
            graphics.drawString(text, x, y);
            graphics.rotate(-Math.toRadians(angle), x, y);

            x += textWidth + 100; // 增加水平间距
            if (x > originalImage.getWidth()) {
                x = 0;
                y += textHeight + 100; // 增加垂直间距
            }
        }

        graphics.dispose();

        // 将处理后的图片转换为输入流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(watermarkedImage, "png", outputStream);
        outputStream.flush();
        InputStream resultStream = new ByteArrayInputStream(outputStream.toByteArray());
        outputStream.close();

        return resultStream;
    }
}